package com.ruoyi.web.controller.procurement;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.procurement.domain.PsGoodsType;
import com.ruoyi.procurement.service.IPsGoodsService;
import com.ruoyi.procurement.service.IPsGoodsTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.procurement.domain.PsProcure;
import com.ruoyi.procurement.service.IPsProcureService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购记录Controller
 * 
 * @author ruoyi
 * @date 2023-10-10
 */
@Api("采购记录")
@RestController
@RequestMapping("/procurement-system/procure")
public class PsProcureController extends BaseController
{
    @Autowired
    private IPsProcureService psProcureService;
    @Autowired
    private IPsGoodsService iPsGoodsService;
    @Autowired
    private IPsGoodsTypeService iPsGoodsTypeService;

    /**
     * 查询采购记录列表
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:list')")
    @GetMapping("/list")
    @ApiOperation("查询采购记录列表")
    public TableDataInfo list(PsProcure psProcure)
    {
        startPage();
        List<PsProcure> list = psProcureService.selectPsProcureList(psProcure);
        return getDataTable(list);
    }

    /**
     * 导出采购记录列表
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:export')")
    @Log(title = "采购记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PsProcure psProcure)
    {
        List<PsProcure> list = psProcureService.selectPsProcureList(psProcure);
        ExcelUtil<PsProcure> util = new ExcelUtil<PsProcure>(PsProcure.class);
        util.exportExcel(response, list, "采购记录数据");
    }

    /**
     * 获取采购记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(psProcureService.selectPsProcureById(id));
    }

    /**
     * 新增采购记录
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:add')")
    @Log(title = "采购记录", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody PsProcure psProcure)
    {
        if (StringUtils.isNotEmpty(psProcure.getPsGoodsTypeId())){
            PsGoodsType psGoodsType = iPsGoodsTypeService.selectPsGoodsTypeById(psProcure.getPsGoodsTypeId());
            if (psGoodsType==null){
                //新增
                PsGoodsType psGoodsType1 = new PsGoodsType();
                psGoodsType1.setPstName(psProcure.getPsGoodsTypeId());
                psGoodsType1.setPstType(psProcure.getPstType());
                psGoodsType1.setPstSpecification(psProcure.getPstSpecification());
                psGoodsType1.setPstStatus(0l);
                iPsGoodsTypeService.insertPsGoodsType(psGoodsType1);
                psProcure.setPsGoodsTypeId(psGoodsType1.getId());
            }
        }else {
            return error("物品名称不能为空！");
        }
        psProcure.setCreateByName(SecurityUtils.getLoginUser().getUser().getNickName());
        if ((psProcure.getPsNum()==null)){
            return error("采购数量不能为空！");
        }
        if ((psProcure.getPsNum().doubleValue()<=0)){
            return error("采购数量不正确！");
        }

        if (psProcure.getPsPrice()==null || psProcure.getPsPrice().doubleValue()<=0){
            psProcure.setPsAmount(new BigDecimal("0.0"));
        }else {
            //计算采购金额
            BigDecimal bigDecimal = psProcure.getPsNum().multiply(psProcure.getPsPrice()).setScale(2, RoundingMode.HALF_UP);
            psProcure.setPsAmount(bigDecimal);
        }

        AjaxResult ajax = toAjax(psProcureService.insertPsProcure(psProcure));
        //同步库存
        iPsGoodsService.deduction(psProcure.getPsGoodsTypeId(),"采购",null,psProcure,null);
        //TODO
        return ajax;
    }

    /**
     * 修改采购记录
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:edit')")
    @Log(title = "采购记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PsProcure psProcure)
    {
//        if ((psProcure.getPsNum()==null || psProcure.getPsPrice()==null)){
//            return error("采购数量 和 采购单价不能为空！");
//        }
//        if ((psProcure.getPsNum().doubleValue()<0 || psProcure.getPsPrice().doubleValue()<0)){
//            return error("采购数量 和 采购单价数量不正确！");
//        }
//        //计算采购金额
//        BigDecimal bigDecimal = psProcure.getPsNum().multiply(psProcure.getPsPrice()).setScale(2, RoundingMode.HALF_UP);
//
//        psProcure.setPsAmount(bigDecimal);
//        return toAjax(psProcureService.updatePsProcure(psProcure));
        return error("历史数据禁止修改！");
    }

    /**
     * 删除采购记录
     */
    @PreAuthorize("@ss.hasPermi('procurement-system:procure:remove')")
    @Log(title = "采购记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(psProcureService.deletePsProcureByIds(ids));
    }
}
